from rest_framework.views import APIView
from utils.result import R
from utils.status_code import StatusCodeEnum 
from utils.aliverify_code import * 
from api.models import ItEduAdv
import random

class AdvAPIView(APIView):
    

    """
    随机获取一个广告
    """
    def get(self,request):
        
        total_num = ItEduAdv.objects.all().count()
        index = random.randint(0,total_num-1)

        adv = ItEduAdv.objects.all()[index]
        
        return R().data_result(adv={
            "title" : adv.title,
            "intro" : adv.intro,
            "image" : adv.image,
            "link" : adv.link
        })
    
    def post(self,request):
        
        title = request.data.get("title")
        intro = request.data.get("intro")
        image = request.data.get("image")
        link = request.data.get("link")

        ItEduAdv.objects.create(
            title = title,
            intro = intro,
            image = image,
            link = link
        )
        
        return R.ok().to_json_response()
        
    
    def delete(self,request):
        # 需要加权限 才能访问接口并删除内容
        _id = request.data.get("_id")

        ItEduAdv.objects.filter(pk=_id).delete()

        return R.ok().to_json_response() 